﻿using Qy.Core;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Qy.Scenario;

[AppService]
public class StatisticsService : QyRepository<Content>
{
    private readonly ApplicationContext _applicationContext;
    private readonly string cacheKey;
    public StatisticsService(ApplicationContext applicationContext) : base(applicationContext)
    {
        _applicationContext = applicationContext;
        cacheKey = CacheConst.CACHE_KEY_STATISTICS;
    }

    /// <summary>
    ///统计常用总数
    /// </summary>
    /// <returns></returns>
    public async Task<NumCount> CountAllAsync()
    {
        string cacheName = cacheKey + "FieldCountAll";
        NumCount count = await _applicationContext.ICacheManager.GetAsync<NumCount>(cacheName);
        if (count == null)
        {
            count = new()
            {
                Content = await Context.Queryable<Content>().CountAsync(),
                User = await Context.Queryable<User>().CountAsync(),
                Log = await Context.Queryable<LogSql>().CountAsync(),
                Notice = await Context.Queryable<NoticeKey>().CountAsync(),
                Member = await Context.Queryable<Member>().CountAsync(),
                CmsCat = await Context.Queryable<ContentCate>().CountAsync(),
                DocPost = await Context.Queryable<DocPost>().CountAsync(),
            };
            await _applicationContext.ICacheManager.SetAsync(cacheName, count, TimeSpan.FromMinutes(10));
        }
        return count;
    }

    /// <summary>
    /// CMS内容
    /// </summary>
    /// <param name="isMonth"></param>
    /// <returns></returns>
    public async Task<List<ContentCount>> CountContentForUserAsync(string isMonth)
    {
        if (isMonth == "month")
        {
            string cacheName = cacheKey + "CountContentForUserAsync";
            List<ContentCount> count = await _applicationContext.ICacheManager.GetAsync<List<ContentCount>>(cacheName);
            if (count == null)
            {
                count = await CountContentForUser(isMonth);
                await _applicationContext.ICacheManager.SetAsync(cacheName, count, TimeSpan.FromMinutes(8));
            }
            return count;
        }
        else
        {
            string cacheName = cacheKey + "CountContentForUserYearAsync";
            List<ContentCount> count = await _applicationContext.ICacheManager.GetAsync<List<ContentCount>>(cacheName);
            if (count == null)
            {
                count = await CountContentForUser(isMonth);
                await _applicationContext.ICacheManager.SetAsync(cacheName, count, TimeSpan.FromMinutes(6));
            }
            return count;
        }

    }

    /// <summary>
    /// 按用户统计发布的信息量 排名
    /// </summary>
    /// <returns></returns>
    public async Task<List<ContentCount>> CountContentForUser(string isMonth)
    {
        var exp = Expressionable.Create<Content>();
        if (isMonth == "month")
            exp = exp.And(data => data.Time.ToString("yyyy-MM") == DateTime.Now.ToString("yyyy-MM"));
        else if (isMonth == "year")
            exp = exp.And(data => data.Time.ToString("yyyy") == DateTime.Now.ToString("yyyy"));
        return await Queryable()
            .LeftJoin<User>((data, user) => data.Uid == user.Id)
            .Where(exp.ToExpression())
            .GroupBy((data) => new { data.Uid })
            .OrderBy(data => data.Uid,OrderByType.Desc)
            .Select((data, user) => new ContentCount()
            {
                Value = SqlFunc.AggregateCount(data.Id),
                Name = user.NickName,
                Uids = data.Uid,
                Status = SqlFunc.AggregateSum(SqlFunc.IF(data.Status).Return(1).End(0))
            })
            .ToListAsync();
    }




    /// <summary>
    /// 查询统计 
    /// </summary>
    //public async Task<List<Statistics>> StatisticsAsync(StatisticsQuery qeuery)
    //{
    //    //string typeString = qeuery.SearchType switch
    //    //{
    //    //    "month" => ",MONTH(`Time`) AS name",
    //    //    "year" => ",YEAR(`Time`) AS name",
    //    //    "category" => ",cate.Name AS name",
    //    //    _ => ",WEEK(`Time`) AS name",
    //    //};
    //    //Sql sql = Sql.Builder;
    //    //sql.Select("COUNT(1) AS value " + typeString + ",SUM(case when mark.Aid=docpost.Id then 1 else 0 end) as MarkNum")
    //    //    .From(DbTableName.OasDocPost + " as docpost")
    //    //    .LeftJoin(DbTableName.QyAdminUser + " as user").On("docpost.Uid = user.Id");
    //    //sql.LeftJoin(DbTableName.OasDocPostMark + " as mark").On("docpost.Id = mark.Aid");
    //    //if (qeuery.SearchType == "category")
    //    //    sql.LeftJoin(DbTableName.OasDocCat + " as cate").On("docpost.Cid = cate.Id");
    //    //if (qeuery.SearchCid != 0)
    //    //    sql.Where("docpost.Cid =@0", qeuery.SearchCid);
    //    //if (!string.IsNullOrEmpty(qeuery.NickName))
    //    //    sql.Where("user.Nickname like @0", "%" + qeuery.NickName + "%");
    //    //if (qeuery.StartDate != null && qeuery.EndDate != null)
    //    //    sql.Where("docpost.Time between @0 AND @1", qeuery.StartDate, qeuery.EndDate);
    //    //sql.Where("user.Id !=1 ");
    //    //sql.GroupBy("name asc");
    //    //return await CreateDAO().FetchAsync<Statistics>(sql);



    //}
}
